<template>
  <div>
    <el-card class="employees-card-bottom">
      <div>
        <!-- form表单 -->

        <formBox
          :key="showText == '收起' ? 0 : 1"
          ref="formBox"
          :notEmployees="notEmployees"
          :total="total"
          :menjinData="menjinData"
          @confirmData="confirmData"
          @handleDelete="handleDelete"
          @opendrawer="$emit('openDrawer', 'addDrawerIsShow', 'add')"
          @showTextFn="showTextFn"
          @confirmCreateuserSubmit="confirmCreateuserSubmit"
        ></formBox>
        <!-- 表格 -->
        <div v-loading="pageLoading">
          <Table
            ref="table"
            :showText="showText"
            :tableData="tableData"
            :total="total"
            :menjinData="menjinData"
            @getList="getList"
            @limitFn="limitFn"
            @multipleSelection="multipleSelection"
            @pageFn="pageFn"
          >
            <template #options="{ data }">
              <el-button v-hasPermi="['hr:archives:check']" type="text" @click="hanldeOptions(data, 'edit')"
                >查看
              </el-button>

              <el-button v-if="data.status !== 0 && data.type !== 1" type="text" @click="hanldeOptions(data, 'worker')"
                >转正</el-button
              >

              <el-button
                v-if="data.type !== 2 || data.status !== 0"
                type="text"
                @click.native="hanldeOptions(data, 'quit')"
              >
                离职
              </el-button>
              <!-- dengshunbo 2024-12-21 -->
              <el-button type="text" v-if="data.is_user_authorize==1" style="color:#999;">人员创建下发</el-button>
              <el-button type="text" v-else @click="hanldeOptions(data, 'doorcreate')">人员创建下发</el-button>
              <el-button type="text" v-if="data.is_user_authorize==1" @click="handlerRowAuth(data)">门禁授权</el-button>
              <!-- <el-button type="text" @click="hanldeOptions(data, 'doorcancel')" v-if="data.is_mj_authorize==1">取消门禁授权</el-button>
              -->
              <!-- end -->
              <el-button v-if="data.status == 0" type="text" @click.native="hanldeOptions(data, 'inviteToJoin')">
                邀请完善信息
              </el-button>

              <el-dropdown v-if="data.type !== 1 && data.status !== 1">
                <span class="el-dropdown-link el-button--text el-button">
                  {{ $t('hr.more') }}
                  <!-- <i class="el-icon-arrow-down el-icon--right" /> -->
                </span>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="data.type !== 1" @click.native="hanldeOptions(data, 'worker')">
                    转正
                  </el-dropdown-item>
                  <el-dropdown-item v-if="data.type !== 1" @click.native="hanldeOptions(data, 'quit')">
                    离职
                  </el-dropdown-item>
                  <el-dropdown-item v-if="data.status !== 1" @click.native="hanldeOptions(data, 'delete')"
                    >删除</el-dropdown-item
                  >
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </Table>
        </div>
      </div>
    </el-card>
    <el-dialog title="批量授权" :visible.sync="dialogdroop" width="60%">
        <selectCommon v-if="dialogdroop" :menjinData="menjinData" @goMenjinFn="goMenjinFn"></selectCommon>
    </el-dialog>
    
    <el-dialog title="授权门禁" :visible.sync="rowauthShow" width="60%">
      <selectUnit v-if="rowauthShow" :loadingunit="loadingunit" :menjinData="menjinData" :selectmenji="selectmenji" @goMenjinFn="goMenjinunitFn"></selectUnit>
        <!-- <div>
          <div>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="outerVisible = false">取 消</el-button>
            <el-button type="primary" @click="innerVisible = true">确定</el-button>
          </div>
        </div> -->
    </el-dialog>
  </div>
</template>

<script>
import { enterpriseCardApi, menjinListCardApi } from '@/api/enterprise'
import myMixins from '../../mixins/method.js'
import select from '@/views/business/components/formSetting/components/form-create-designer/src/config/rule/select.js';
import { VxeTable } from 'vxe-table';
export default {
  mixins: [myMixins],
  data() {
    return {
      fromTab: {},
      tableData: [],
      pageLoading: false,
      isShownewPersonnel: false,
      showText: '展开',
      total: 0,
      page: 1,
      limit: 15,
      selection: [],
      notEmployees: '在职',
      // dengshunbo 2024-12-21 门禁列表数据
      menjinData:[],
      dialogdroop: false,
      selectdrooaData:[],
      authRow:null,
      rowauthShow: false,
      selectmenji:[],
      loadingunit: false,
      infoindex: 0,
      // end
    }
  },

  
  created() {
    this.menjinCardAuth();
    this.getList()
  },

  methods: {
    // 筛选条件
    confirmData(from) {
      this.fromTab = { ...from }
      if (JSON.stringify(from) == '{}') {
        this.$refs.table.where.limit = 15
      }
      if (this.$refs.formBox.tableFrom.exportType === 1) {
        this.fromTab.limit = 0
        this.fromTab.page = 0
        this.fromTab.types = [1, 2, 3]
        this.getExportData(this.fromTab)
      } else {
        this.page = 1
        this.getList(1)
        this.$refs.table.where.page = 1
      }
    },
    // 批量人员创建下发/门禁授权/取消门禁授权
    confirmCreateuserSubmit(index){
        let selecttableData = this.selection;
        if(selecttableData.length > 0){
        if(index==3){ // 批量授权
            let selectData = this.handlerReturnTable(selecttableData, 2);
            if(selectData.length > 0){
              this.selectdrooaData = selectData;
              this.dialogdroop = true;
            }else{
              this.selectdrooaData = []
              this.$message.error('请检查员工数据是否已经创建下发或都已授权,已授权无法再次授权，请取消授权后再操作');
            }
        }else if(index==2){ // 批量取消授权
          let selectData = this.handlerReturnTable(selecttableData, 3);
            if(selectData.length > 0){
              // 弹窗确认取消授权吗
              this.$confirm('你确定要批量取消授权, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.pageLoading = true;
                this.selectdrooaData = selectData;
                this.$emit('opendoorAuth', selectData, 'doorcancel', 3)
              }).catch(() => {
                    
              });
            }else{
              this.selectdrooaData = []
              this.$message.error('请检查员工数据是否已授权');
            }
          
        }else{ // 批量下发
          let selectData = this.handlerReturnTable(selecttableData, 1);
          if(selectData.length > 0){
            this.pageLoading = true;
            this.$emit('opendoorAuth', selectData, 'doorcreate', 3)
          }else{
            this.$message.error('请检查员工数据是否已经创建下发或都已有工号操作');
          }
        }
      }else{
        this.$message.error('请选择要批量下发或授权人员');
      }
    },
    // 批量门禁授权提交方法
    goMenjinFn(index=1, doordata=''){
        if(index==1){ // 取消
            this.dialogdroop = false;
        }else{
            this.dialogdroop = false;
            this.pageLoading = true;
            this.$emit('opendoorAuth', this.selectdrooaData, 'doorauth', 3, doordata)
        }
    },
    goMenjinunitFn(item, index=0){
      this.loadingunit = true;
      this.infoindex = index;
      this.$emit('opendoorAuth', this.authRow, 'doorcancel', 7, item)
      // if(index == 1){ // 取消授权
      //   this.$emit('opendoorAuth', this.authRow, 'doorcancel', 7, item)
      // }else if(index==2){ // 授权
      //   this.$emit('opendoorAuth', this.authRow, 'doorcancel', 7, item)
      // }
       
    },
    handlerReturnTable(selecttableData, index=1){
        let selectData = [];
        for(let i=0;i<selecttableData.length;i++){
            let item = selecttableData[i];
            if(index==1){  // 批量下发
              if(item.is_user_authorize != 1 && item.gong_hao !=''){   // 人员未下发
                  let obj = {};
                  obj.uid = item.uid;
                  obj.id = item.id;
                  selectData.push(obj);
              }
            }else if(index==2){ // 批量授权
              if(item.is_user_authorize == 1 && item.is_mj_authorize !=1){ // 人员已下发未授权
                let obj = {};
                obj.uid = item.uid;
                obj.id = item.id;
                obj.is_mj_authorize = item.is_mj_authorize;
                obj.mj_member_sn = item.mj_member_sn;
                selectData.push(obj);
              }
            }else{ // 批量取消授权
           
              if(item.is_user_authorize == 1 && item.is_mj_authorize ==1){ // 取消人员授权
                  let obj = {};
                  obj.uid = item.uid;
                  obj.id = item.id;
                  obj.is_mj_authorize = item.is_mj_authorize;
                  obj.mj_member_sn = item.mj_member_sn;
                  selectData.push(obj);
              }
            }
        }
        return selectData;
    },
    // 分页
    limitFn(val) {
      this.limit = val
      this.getList(1)
    },
    pageFn(page) {
      this.page = page
      this.getList(1)
      
    },

    // 获取列表数据
    getList(val, row='') {
      if (val == 1) {
      }else if(val==9){
         this.loadingunit = false;
         this.$message.success(this.infoindex==1?'取消授权成功':'门禁授权成功')
         this.handlerRowupdate(this.selectmenji);
      }else if(val==6){
         this.handlerRowAuth(row)
      } else {
        this.fromTab = {}
      }

      this.fromTab.limit = this.limit
      this.fromTab.page = this.page
      this.fromTab.types = [1, 2, 3]
      this.pageLoading = true
      enterpriseCardApi(this.fromTab)
        .then((res) => {
          this.tableData = res.data.list
          if (this.tableData && this.tableData.length > 0) {
            this.tableData.map((value) => {
              if (value.frames.length > 1) {
                value.frames.sort((a, b) => {
                  return b.is_mastart - a.is_mastart
                }) //升序
              }
            })
          }
          this.total = res.data.count
          this.pageLoading = false
        })
        .catch((err) => {})
        .finally(() => {
          this.pageLoading = false
        })
    },
 
    // 门禁组列表数据 dengshunbo 2024-12-21 门禁列表数据
    menjinCardAuth() {
      let dataform = {page:1, limit: 100,scope_frame:'all', show_search_type:'0', is_system:1, view_search_boolean:'', view_search:[],order_by:[]}
      menjinListCardApi(dataform)
        .then((res) => {
           if(res.status==200){
              this.menjinData = res.data.list;
           }
        })
        .catch((err) => {})
        .finally(() => {
       
        })
        this.isdoorAuth = 1;
    },
    getpageLoading(){
        this.pageLoading = false;
    },
    // end

    // 展开
    showTextFn(val) {
      this.showText = val
    },

    // 多选表格
    multipleSelection(val) {
      this.selection = val
    },
    handlerauthTime(){
        const now = new Date();
        const year = now.getFullYear();
        const month = now.getMonth() + 1 > 9 ? now.getMonth() + 1 : '0' + (now.getMonth() + 1); // 月份从0开始，需要加1
        const day = now.getDate() > 9 ? now.getDate() : '0' + now.getDate();
        return year + 10 + '-' + month + '-' + day;
    },
    handlerRowAuth(data){
      this.authRow = data;
      let accessarray = []
      let accessteam = data.access_control_team;
      accessarray = (accessteam.split(",")).map(Number);
      if(accessarray && accessarray.length > 0){
          this.handlerRowupdate(accessarray)
      }
    },
    handlerRowupdate(accessData){
      let authtime = this.handlerauthTime();
      let mjdata = [];
      if(accessData){
        for(let i=0;i<this.menjinData.length;i++){
            this.menjinData[i].isauth = false;
            this.menjinData[i].auth_time = authtime;
            if(accessData.includes(this.menjinData[i].id)){
               this.menjinData[i].isauth = true;
            }
            mjdata.push(this.menjinData[i])
        }
      }
      this.selectmenji = accessData;
      this.menjinData = mjdata;
      this.rowauthShow = true;
    },
    hanldeOptions(data, type) {
      switch (type) {
        // 邀请加入
        case 'invite': {
          this.$emit('invitation', data, type)
          break
        }
        // 邀请完善信息
        case 'inviteToJoin': {
          this.$emit('invitation', data, type)
          break
        }

        // 编辑
        case 'edit': {
          this.$emit('openDrawer', 'addDrawerIsShow', 'edit', data)
          break
        }

        // 离职
        case 'quit': {
          this.$emit('onQuit', data)
          break
        }

        // 转正
        case 'worker': {
          this.$emit('onWorker', data)
          break
        }

        // 删除
        case 'delete': {
          this.$emit('onDelete', data)
          break
        }

         // 门禁相关-人员创建-dengshunbo-2024,12,19
         case 'doorcreate': {
          this.pageLoading = true;
          this.$emit('opendoorAuth', data, 'doorcreate', 1)
          break
        }
        // 门禁相关-门禁授权-dengshunbo-2024,12,19
        case 'doorauth': {
          this.$emit('opendoorAuth', data, 'doorauth', 3)
          break
        }
        // 门禁相关-取消门禁授权-dengshunbo-2024,12,19
        case 'doorcancel': {
          this.$emit('opendoorAuth',   data, 'doorcancel', 2)
          break
        }
      }
    }
  },

  components: {
    formBox: () => import('../formBox.vue'),
    Table: () => import('../table.vue'),
    selectCommon: () => import('@/components/common/selectCommon'),
    selectUnit: () => import('@/components/common/selectUnit'),

  }
}
</script>

<style lang="scss" scoped>
.divBox {
  margin: 0;
}
.add-height {
  height: 250px !important;
}
.alert {
  height: 42px;
  background: #edf5ff;
  border: 1px solid #97c3ff;
  border-radius: 6px;
  line-height: 42px;
  font-size: 13px;
  font-weight: 400;
  color: #606266;
  padding-left: 20px;
  margin-bottom: 30px;
}
.look {
  font-style: italic;
  cursor: pointer;
}
/deep/ .el-card{
  padding-bottom:36px;
}
/deep/ .el-button--medium{
  padding-top:6px;padding-bottom:6px;
}
</style>
